package com.moujitx.aliyuniot.control.app;

import android.os.Looper;
import android.text.method.ScrollingMovementMethod;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

    //连接参数
    String pub_topic = "";
    String sub_topic = "";
    String clientId = "";
    String mqttHostUrl = "";
    String username = "";
    String password = "";


    private String device_log;
    private MqttClient client;
    private MqttConnectOptions options;
    private Handler handler;
    private ScheduledExecutorService scheduler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tv_humidity = findViewById(R.id.tv_humidity);
        TextView tv_mqtt = findViewById(R.id.tv_mqtt);
        TextView tv_mode = findViewById(R.id.tv_mode);
        TextView tv_switch = findViewById(R.id.tv_switch);
        TextView tv_device = findViewById(R.id.tv_device);
        TextView tv_log = findViewById(R.id.tv_log);
        TextView tv_devNow = findViewById(R.id.tv_devNow);

        Button btn_open = findViewById(R.id.btn_open);
        Button btn_close = findViewById(R.id.btn_close);
        Button btn_dev01 = findViewById(R.id.btn_dev01);
        Button btn_dev02 = findViewById(R.id.btn_dev02);
        Button btn_devClose = findViewById(R.id.btn_devClose);

        btn_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开
                publish_message("{\"params\":{\"LEDSwitch\":1},\"version\":\"1.0.0\"}");
            }
        });

        btn_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关
                publish_message("{\"params\":{\"LEDSwitch\":0},\"version\":\"1.0.0\"}");
            }
        });

        btn_devClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭所有连接
                disconnect();
                tv_devNow.setText("--");
                device_log = "----Close All Connected----" + "\n\n" + device_log;
                tv_log.setText(device_log);
                tv_log.setMovementMethod(ScrollingMovementMethod.getInstance());
            }
        });

        btn_dev01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                disconnect();
                //dev01
                clientId = "icmzmjztnzv.device_app|securemode=2,signmethod=hmacsha256,timestamp=1696903875970|";
                mqttHostUrl = "tcp://iot-06z00f41p02vz6s.mqtt.iothub.aliyuncs.com:1883";
                username = "device_app&icmzmjztnzv";
                password = "6f4c09797c54d1096151dbbc0b10ab9f5d457c0f21dabb7c683f707c8b285bc6";

                pub_topic = "/sys/icmzmjztnzv/device_app/thing/event/property/post";
                sub_topic = "/sys/icmzmjztnzv/device_app/thing/service/property/set";

                tv_devNow.setText("设备01");
                device_log = "----Device01 Connected----" + "\n\n" + device_log;
                tv_log.setText(device_log);
                tv_log.setMovementMethod(ScrollingMovementMethod.getInstance());

                mqtt_init();
                start_reconnect();
            }
        });

        btn_dev02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                disconnect();
                //dev02
                clientId = "icmzmjztnzv.device02_app|securemode=2,signmethod=hmacsha256,timestamp=1696903510295|";
                mqttHostUrl = "tcp://iot-06z00f41p02vz6s.mqtt.iothub.aliyuncs.com:1883";
                username = "device02_app&icmzmjztnzv";
                password = "4a36aa686c8d99f17691a454db8c7291867bad11a710fb141b43fcc14eb8f4e5";

                pub_topic = "/sys/icmzmjztnzv/device02_app/thing/event/property/post";
                sub_topic = "/sys/icmzmjztnzv/device02_app/thing/service/property/set";

                tv_devNow.setText("设备02");
                device_log = "----Device02 Connected----" + "\n\n" + device_log;
                tv_log.setText(device_log);
                tv_log.setMovementMethod(ScrollingMovementMethod.getInstance());

                mqtt_init();
                start_reconnect();
            }
        });



        handler = new Handler(Looper.myLooper()) {
            @SuppressLint("SetTextI18n")
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1: //开机校验更新回传
                        break;
                    case 2:  // 反馈回传
                        break;
                    case 3:  //MQTT 收到消息回传   UTF8Buffer msg=new UTF8Buffer(object.toString());
                        String message = msg.obj.toString();
                        try {
                            JSONObject jsonObjectALL = null;
                            jsonObjectALL = new JSONObject(message);

                            device_log = jsonObjectALL.toString() + "\n\n" + device_log;
                            tv_log.setText(device_log);
                            tv_log.setMovementMethod(ScrollingMovementMethod.getInstance());

                            //设置离线
                            if (jsonObjectALL.has("status")) {
                                String device_status = jsonObjectALL.getString("status");
                                if (device_status.equals("offline")) {
                                    tv_device.setText("离线");
                                    Toast.makeText(MainActivity.this, "设备已离线", Toast.LENGTH_SHORT).show();
                                    break;
                                }
                            } else {
                                //设备参数
                                if (jsonObjectALL.getJSONObject("items").has("Humidity")) {
                                    int humidity = jsonObjectALL.getJSONObject("items").getJSONObject("Humidity").getInt("value");
                                    tv_humidity.setText(humidity + "");
                                }
                                if (jsonObjectALL.getJSONObject("items").has("Mode")) {
                                    int mode = jsonObjectALL.getJSONObject("items").getJSONObject("Mode").getInt("value");
                                    if (mode == 0) tv_mode.setText("自动模式"); else tv_mode.setText("手动模式");
                                }
                                if (jsonObjectALL.getJSONObject("items").has("LEDSwitch")) {
                                    int ledSwitch = jsonObjectALL.getJSONObject("items").getJSONObject("LEDSwitch").getInt("value");
                                    if (ledSwitch == 0) tv_switch.setText("关"); else tv_switch.setText("开");
                                }
                            }

                            tv_device.setText("在线");
                        } catch (JSONException e) {
                            e.printStackTrace();
                            break;
                        }
                        break;
                    case 30:  //连接失败
                       // Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                        tv_mqtt.setText("未连接");

                        tv_humidity.setText("--");
                        tv_mode.setText("--");
                        tv_switch.setText("--");
                        tv_device.setText("离线");
                        break;
                    case 31:   //连接成功
                        Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                        tv_mqtt.setText("已连接");

                        tv_humidity.setText("--");
                        tv_mode.setText("--");
                        tv_switch.setText("--");
                        tv_device.setText("离线");
                        try {
                            client.subscribe(sub_topic, 1);
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        break;
                }
            }
        };
    }

    private void mqtt_init() {
        try {

            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            System.out.println(">>>" + mqttHostUrl);
            System.out.println(">>>" + clientId);

            //connectMqtt(targetServer, mqttclientId, mqttUsername, mqttPassword);

            client = new MqttClient(mqttHostUrl, clientId, new MemoryPersistence());
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(false);
            //设置连接的用户名
            options.setUserName(username);
            //设置连接的密码
            options.setPassword(password.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(60);
            //设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    System.out.println("connectionLost----------");
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    System.out.println("deliveryComplete---------" + token.isComplete());
                }

                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                    //subscribe后得到的消息会执行到这里面
                    System.out.println("messageArrived----------");
                    Message msg = new Message();
                    //封装message包
                    msg.what = 3;   //收到消息标志位
                    msg.obj =message.toString();
                    //发送messge到handler
                    handler.sendMessage(msg);    // hander 回传
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void mqtt_connect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!(client.isConnected()))  //如果还未连接
                    {
                        client.connect(options);
                        Message msg = new Message();
                        msg.what = 31;
                        // 没有用到obj字段
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 30;
                    // 没有用到obj字段
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }
    private void start_reconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    mqtt_connect();
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }

    public void disconnect() {
        try {
            client.disconnect();
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void publish_message(String message) {
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage mqtt_message = new MqttMessage();
        mqtt_message.setPayload(message.getBytes());
        try {
            client.publish(pub_topic, mqtt_message);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}